package org.yinweichen.llm_dataset_backend.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yinweichen.llm_dataset_backend.DTO.*;
import org.yinweichen.llm_dataset_backend.entity.OriginalQuestion;
import org.yinweichen.llm_dataset_backend.entity.StandardQuestion;
import org.yinweichen.llm_dataset_backend.service.*;
import org.yinweichen.llm_dataset_backend.util.QAReader;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/io")
public class InputOutputController {
    private final OriginalQuestionService originalQuestionService;
    private final OriginalAnswerService originalAnswerService;
    private final StandardQuestionService standardQuestionService;
    private final StandardAnswerService standardAnswerService;
    private final PointsService pointsService;

    public InputOutputController(OriginalQuestionService originalQuestionService,
                              OriginalAnswerService originalAnswerService,
                              StandardQuestionService standardQuestionService,
                             PointsService pointsService,
                             StandardAnswerService standardAnswerService) {
        this.originalQuestionService = originalQuestionService;
        this.standardQuestionService = standardQuestionService;
        this.standardAnswerService=standardAnswerService;
        this.originalAnswerService=originalAnswerService;
        this.pointsService=pointsService;
    }
    /*
        TODO:数据导入
        批量导入格式：原始问答对+标准问答对，通过"source_question_id"进行绑定。
     */
    @PostMapping("/input/{version}")
    public ResponseEntity<?> inputQA(
            @PathVariable("version") String version,
            @RequestParam("originalFile") MultipartFile originalFile,
            @RequestParam("standardFile") MultipartFile standardFile) {
        try {
            // 1. 检查文件是否为空
            if (originalFile.isEmpty() || standardFile.isEmpty()) {
                return ResponseEntity.badRequest().body("请上传原始问答对和标准问答对两个文件");
            }

            // 2. 验证文件类型
            if (!originalFile.getOriginalFilename().endsWith(".json") ||
                !standardFile.getOriginalFilename().endsWith(".json")) {
                return ResponseEntity.badRequest().body("只支持JSON格式文件");
            }

            // 3. 创建临时文件保存上传内容
            File originalTempFile = File.createTempFile("upload-original-", ".json");
            originalFile.transferTo(originalTempFile);

            File standardTempFile = File.createTempFile("upload-standard-", ".json");
            standardFile.transferTo(standardTempFile);

            // 4. 读取文件内容
             List<QAReader.OriginalQA> originalQAs = QAReader.loadOriginalQA(originalTempFile.getAbsolutePath());
             List<QAReader.StandardQA> standardQAs = QAReader.loadStandardQA(standardTempFile.getAbsolutePath());

            // 5. 处理数据关联关系
            // TODO: 实现关联逻辑
            for (QAReader.OriginalQA originalQA : originalQAs) {
                OriginalQuestionCreateDTO originalRequest = new OriginalQuestionCreateDTO(
                        originalQA.getQuestionTitle(),
                        originalQA.getQuestionBody(),
                        originalQA.getSourceUrl()
                );
                ResponseEntity<OriginalQuestion> org_response=originalQuestionService.createQuestion(version,originalRequest);
                //TODO: 创建原始问题
                OriginalAnswerCreateDTO ansRequest1=new OriginalAnswerCreateDTO(
                        originalQA.getAnswerBody(),
                        org_response.getBody().getId(),
                        version
                );
                //创建原始回答
                originalAnswerService.create(ansRequest1);
                // 查找对应的标准问答对
                int sourceQuestionId=originalQA.getSourceQuestionId();
                for (QAReader.StandardQA standardQA : standardQAs) {
                    if (standardQA.getSourceQuestionId()==sourceQuestionId) {
                        // 创建标准问题请求对象
                        StandardQuestionCreateDTO standardRequest = new StandardQuestionCreateDTO(
                                standardQA.getQuestion(),
                                org_response.getBody().getId(),
                                version,
                                "default"
                        );
                        // 创建标准问题
                        ResponseEntity<StandardQuestion> stand_response=standardQuestionService.create(standardRequest);
                        //创建标准回答
                        StandardAnswerCreateDTO ansRequest2=new StandardAnswerCreateDTO(
                                standardQA.getAnswer(),
                                stand_response.getBody().getId(),
                                version
                        );
                        standardAnswerService.create(ansRequest2);
                        for(String keyPoint:standardQA.getKeyPoints()){
                            PointsCreateDTO pointsRequest=new PointsCreateDTO(
                                    keyPoint,
                                    stand_response.getBody().getId(),
                                    version,
                                    1
                            );
                            //创建关键点
                            pointsService.createPoint(pointsRequest);
                        }

                    }
                }
            }

            return ResponseEntity.ok("文件导入成功");
        } catch (IOException e) {
            return ResponseEntity.internalServerError().body("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("导入失败: " + e.getMessage());
        }
    }


}
